// 导入所需的包
import 'package:flutter/material.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

// 用户列表页面，使用HookWidget管理状态
class UserListPage extends HookWidget {
  const UserListPage({super.key});

  @override
  Widget build(BuildContext context) {
    // 当前页码状态，默认为第1页
    final currentPage = useState(1);
    // 每页显示的记录数
    final pageSize = 10;
    // 总记录数状态
    final totalRecords = useState(0);
    // 用户控制器，用于获取用户数据
    final userController = useMemoized(() => UserController());
    // 用户列表状态
    final users = useState<List<User>>([]);

    // 加载用户数据的回调函数
    final loadUsers = useCallback(() async {
      // 调用控制器获取用户数据
      await userController.fetchUsers(currentPage.value, pageSize);
      // 更新总记录数和用户列表
      totalRecords.value = userController.totalRecords;
      users.value = userController.users;
    }, [currentPage.value, userController]);

    // 页面加载时调用loadUsers函数
    useEffect(() {
      loadUsers();
      return null;
    }, [loadUsers]);

    // 页面改变处理函数
    void onPageChanged(int page) {
      currentPage.value = page;
    }

    // 构建分页控件
    Widget buildPaginationControls() {
      // 计算总页数
      int totalPages = (totalRecords.value / pageSize).ceil();

      return Container(
        padding: EdgeInsets.all(16),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 首页按钮
            IconButton(
              icon: Icon(Icons.first_page),
              onPressed: currentPage.value <= 1 ? null : () => onPageChanged(1),
            ),
            // 上一页按钮
            IconButton(
              icon: Icon(Icons.arrow_back),
              onPressed: currentPage.value <= 1
                  ? null
                  : () => onPageChanged(currentPage.value - 1),
            ),
            // 当前页信息显示
            Text('Page ${currentPage.value} of $totalPages'),
            // 下一页按钮
            IconButton(
              icon: Icon(Icons.arrow_forward),
              onPressed: currentPage.value >= totalPages
                  ? null
                  : () => onPageChanged(currentPage.value + 1),
            ),
            // 末页按钮
            IconButton(
              icon: Icon(Icons.last_page),
              onPressed: currentPage.value >= totalPages
                  ? null
                  : () => onPageChanged(totalPages),
            ),
          ],
        ),
      );
    }

    // 构建页面UI
    return Scaffold(
      appBar: AppBar(title: Text('User List')),
      body: Column(
        children: [
          Expanded(
            child: users.value.isEmpty
                // 如果用户列表为空，显示加载指示器
                ? Center(child: CircularProgressIndicator())
                // 否则显示数据表格
                : SfDataGrid(
                    source: UserDataSource(users.value),
                    columns: [
                      GridColumn(
                        columnName: 'id',
                        label: Text('User ID'),
                        width: 100,
                      ),
                      GridColumn(
                        columnName: 'userName',
                        label: Text('User Name'),
                        width: 150,
                      ),
                      GridColumn(
                        columnName: 'nickName',
                        label: Text('Nickname'),
                        width: 150,
                      ),
                      GridColumn(
                        columnName: 'department',
                        label: Text('Department'),
                        width: 200,
                      ),
                      GridColumn(
                        columnName: 'phoneNumber',
                        label: Text('Phone Number'),
                        width: 150,
                      ),
                    ],
                  ),
          ),
          // 添加分页控件
          buildPaginationControls(),
        ],
      ),
    );
  }
}

// 用户数据模型类
class User {
  final int id;
  final String userName;
  final String nickName;
  final String department;
  final String phoneNumber;

  User({
    required this.id,
    required this.userName,
    required this.nickName,
    required this.department,
    required this.phoneNumber,
  });
}

// 用户数据控制器类
class UserController {
  List<User> users = [];
  int totalRecords = 0;

  // 获取用户数据的方法
  Future<void> fetchUsers(int page, int pageSize) async {
    // 模拟API调用延迟
    await Future.delayed(Duration(milliseconds: 200));

    // 计算起始索引
    final startIndex = (page - 1) * pageSize;

    // 生成模拟数据（实际应用中应从API获取）
    final mockData = List.generate(
      50,
      (index) => User(
        id: index + 1,
        userName: 'user${index + 1}',
        nickName: 'nickname${index + 1}',
        department: 'Department ${(index % 5) + 1}',
        phoneNumber: '138${(10000000 + index).toString().substring(1)}',
      ),
    );

    // 根据分页参数获取当前页数据
    users = mockData.skip(startIndex).take(pageSize).toList();
    totalRecords = mockData.length;
  }
}

// 用户数据源类，用于为数据表格提供数据
class UserDataSource extends DataGridSource {
  List<User> users;

  UserDataSource(this.users);

  // 获取数据行
  @override
  List<DataGridRow> get rows => users
      .map(
        (user) => DataGridRow(
          cells: [
            DataGridCell<int>(columnName: 'id', value: user.id),
            DataGridCell<String>(columnName: 'userName', value: user.userName),
            DataGridCell<String>(columnName: 'nickName', value: user.nickName),
            DataGridCell<String>(
              columnName: 'department',
              value: user.department,
            ),
            DataGridCell<String>(
              columnName: 'phoneNumber',
              value: user.phoneNumber,
            ),
          ],
        ),
      )
      .toList();

  // 构建行组件
  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    return DataGridRowAdapter(
      cells: row.getCells().map<Widget>((dataGridCell) {
        return Container(
          alignment: Alignment.centerLeft,
          padding: EdgeInsets.all(8.0),
          child: Text(dataGridCell.value.toString()),
        );
      }).toList(),
    );
  }
}
